package com.leetao.dingtalk.core.service.impl;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.leetao.dingtalk.core.config.DingTalkProperties;
import com.leetao.dingtalk.core.domain.Token;
import com.leetao.dingtalk.core.domain.rest.Rest;
import com.leetao.dingtalk.core.service.DingTalkAuthService;
import com.leetao.dingtalk.core.support.DingTalkResponseToRestConverter;
import com.taobao.api.ApiException;

import static com.leetao.dingtalk.core.constant.HttpConstants.*;
import static com.leetao.dingtalk.core.constant.DingTalkApis.*;

/**
 * 钉钉验证服务
 *
 * @author 菅江晖
 * @date 2021/5/24 - 11:20
 */
public class DingTalkAuthServiceImpl implements DingTalkAuthService {

    private final DingTalkProperties dingTalkProperties;

    public DingTalkAuthServiceImpl(DingTalkProperties dingTalkProperties) {
        this.dingTalkProperties = dingTalkProperties;
    }


    @Override
    public Rest<Token> getToken() throws ApiException {
        DingTalkClient client = new DefaultDingTalkClient(GET_TOKEN);
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setAppkey(dingTalkProperties.getAppKey());
        req.setAppsecret(dingTalkProperties.getAppSecret());
        req.setHttpMethod(GET);
        OapiGettokenResponse resp = client.execute(req);

        return DingTalkResponseToRestConverter.convertToken(resp);
    }
}


